
package com.google.code.gestion_de_conferences;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;

import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class AddroomActivity extends Activity {

	AABDatabaseManager db;
	Button addRoom_btn;
	EditText reg_room_name,reg_address,reg_capacity,reg_description;
	TextView reg_room_name_error,  reg_address_error ,reg_capacity_error ;
	int roomPosition;
	
	/**
	 * @author Rayan Zahab
	 * @param Bundle
	 */
	@Override
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Set View to register.xml
        setContentView(R.layout.addroom);
       
        db = new AABDatabaseManager(this);
        
        addRoom_btn = (Button) findViewById(R.id.btn_add);
        reg_room_name = (EditText) findViewById(R.id.reg_roomname);
        reg_address = (EditText) findViewById(R.id.reg_roomaddress);
        reg_capacity = (EditText) findViewById(R.id.reg_roomcapacity);
        reg_description = (EditText) findViewById(R.id.reg_roomdescription);   
        
        reg_room_name_error = (TextView) findViewById(R.id. reg_roomname_error);
	 	reg_address_error = (TextView) findViewById(R.id.reg_roomaddress_error);
	 	reg_capacity_error = (TextView) findViewById(R.id.reg_roomcapacity_error);
                
        //This is to get the position of the selected item from the roomssList if we chose to edit the room
        Intent usersListIntent = getIntent(); 
       
        //-1 is the default value of the selectedRoomId. This value will specify that no room was selected
        roomPosition = usersListIntent.getIntExtra("selectedRoomPosition", -1);    
       
        //we are editing a user
        if (roomPosition != -1)
        {	
        	//change the activity title
        	setTitle("Edit Room");
        	
        	//change button text
        	addRoom_btn.setText("Edit Room");
        	
        	//populate form with correct data if we are editing the user
        	populateForm(roomPosition);
        	
        }
        addRoom_btn.setOnClickListener
    	(
    		new View.OnClickListener()
	    	{
				@Override public void onClick(View v) {
					String room_name = reg_room_name.getText().toString();
			    	String address = reg_address.getText().toString();
			    	String capacity = reg_capacity.getText().toString();
			    	String description = reg_description.getText().toString();
			    	
		    		addRoom(roomPosition,room_name,address,capacity,description);
			    			    	
				}
			}
    	);
    }
	
	
	 /**
	 * This function clears all errors in add room page
	 * @author Hyame Alameddine <halameddine@gmail.com> 
	 */
	private void clearErrors()
	{	
		reg_room_name_error.setText( "");
	 	reg_address_error.setText("");
	 	reg_capacity_error.setText("");
       
    }
	
	/**
	 * Validates the room info
	 * 
	 * @author Hyame Alameddine <hyame.alameddine@gmail.com>
	 * 
	 * @param room_name
	 * @param address
	 * @param capacity
	 * @return
	 */
	public boolean validate(String room_name, String address, String capacity)
	{
		 //first clear all error fields 
        clearErrors();
      
        Boolean error = false;
       
        if(room_name.length() == 0)
        {
            error = true;
            reg_room_name_error.setText( "Room name is a required field!");
        }
      
        if(address.length() == 0)
        {
            error = true;
            reg_address_error.setText(  "Room address is a required field!");
        }
        
       try
       {
           Integer.parseInt(capacity.toString()); 
    	
       }
       catch (Exception e)
       {
    	    error = true;
           reg_capacity_error.setText(  "Room capacity should be a number!");
           e.printStackTrace();
    	   
       }        
      
        return error;
	
	}
	
	/**
	 * 
	 * @param name
	 * @param address
	 * @param capacity
	 * @param description
	 */
	public void addRoom(int position,String name,String address,String capacity,String description)
	{
		boolean error = validate(name,address,capacity);
    	
		if(!error)
		{
    		
			try
			{
				Room r = new Room();
		  		r.setAddress(address);
	    		r.setCapacity(capacity);
	    		r.setDescription(description);
	    		r.setName(name);
	    		
	    		
	    		//Check if we have an item selected to edit or we are adding a new room
				if (position != -1)
				{	
					ArrayList<Object> dbRoom = new ArrayList<Object>();
		 	 	
		 		
					//get the selected user data
					 dbRoom = db.getObjectFromPosition(position, r);
					
					//set the user id to edit
					r.setId(Integer.parseInt(dbRoom.get(0).toString()));
					
					//update row
					db.updateRow (r);
					
					//success msg
					Toast.makeText(this, "Room successfully edited", Toast.LENGTH_LONG).show();
			         
				}				
	    		else
	    		{
	    			// adding a new room
	    			db.insertRow(r);
	    			Toast.makeText(this, "Room successfully added", Toast.LENGTH_LONG).show();	
	    		}
	
		    	Intent i = new Intent(getApplicationContext(), RoomsListActivity.class);
		        startActivity(i);
	    		
	    	}
			catch (Exception e)
        	{
        		Log.e("Update Error", e.toString());
        		e.printStackTrace();
        	}
		}
		
	}
	/**
 	 * Populates the form with the clicked room data
 	 * 
 	 * @author Hyame Alameddine <hyame.alameddine@gmail.com>
 	 * 
 	 * @param position position of the clicked room
 	 */
 	private void populateForm (int position)
 	{	 		
 		Room room = new Room();
 		ArrayList<Object> dbRoom = new ArrayList<Object>();
 	
 		//get the user object from the db
 		dbRoom = db.getObjectFromPosition(position, room);
 	 		
 		//populate the form
 		reg_room_name.setText(dbRoom.get(1).toString()); 
 		reg_address.setText(dbRoom.get(2).toString());
 		reg_capacity.setText(dbRoom.get(3).toString());
 		reg_description.setText(dbRoom.get(4).toString()); 		
 		
 	}
 	
 	 /**
	   * This function create the menu options 
	   * @author Rayan Zahab <differentruna@gmail.com> 
	   * @param menu
	   */
	 @Override
	 public boolean onCreateOptionsMenu(Menu menu) {
	     MenuInflater inflater = getMenuInflater();
	     inflater.inflate(R.menu.menu, menu);              
	     return true;
	 }
	 
	 /**
	   * This function handles clicking any of the menu's items
	   * @author Rayan Zahab <differentruna@gmail.com> 
	   * @author Hyame Alameddine <hyame.alameddine@gmail.com>
	   * @param menu
	   */
	 @Override
	 public boolean onOptionsItemSelected(MenuItem item) 
	  {	  
		  Intent i;
		  
		  switch (item.getItemId()) 
		  {
	           
	          case R.id.users:     
	            	i = new Intent(getApplicationContext(), UsersListActivity.class);
	            	startActivity(i);
	                break;
	          case R.id.reservations:     
	            	i = new Intent(getApplicationContext(), ReservationsListActivity.class);
	            	startActivity(i);
	                break;
	          case R.id.conferences:     
	            	i = new Intent(getApplicationContext(), RoomsListActivity.class);
	            	startActivity(i);
	                break;
	          case R.id.edit_profile: 	        	  
	            	i = new Intent(getApplicationContext(), RegisterActivity.class);
	            	i.putExtra("editAdmin", 1);
	            	startActivity(i);
	                break;
	          case R.id.logout: 
	            	i = new Intent(getApplicationContext(), LoginActivity.class);
	            	startActivity(i);
	                break;
	          case R.id.help:     
	                AlertDialog alertDialog = new AlertDialog.Builder(this).create();
	                alertDialog.setTitle("Help!");
	                alertDialog.setMessage("Gestion de conference is an application helps you manage reservations, add rooms ,add users and reserve rooms to organize conferences !");
	                alertDialog.setIcon(R.drawable.icon);
	                alertDialog.show();
	                break;
	          case R.id.developers: 
	            	Toast.makeText(this, "Rayan,Hyam,Mostafa!", Toast.LENGTH_LONG).show();
	                break;
	         
	        }
	        return true;
	    }

}
